#include "keyevent.h"

#include <QKeyEvent>

KeyEvent::KeyEvent(QWidget *parent)
	: QLabel{parent}
{
	setStyleSheet("background-color: skyblue");
	this->setFocusPolicy(Qt::StrongFocus);
	this->setFixedSize(50,50);
	this->getParent_size();
}

void KeyEvent::getParent_size()
{
	QWidget * parent=this->parentWidget();
	if(parent != nullptr){
		this->parent_h=parent->height();
		this->parent_w=parent->width();
	}else {
		this->parent_h=0;
		this->parent_w=0;
	}
}

void KeyEvent::keyPressEvent(QKeyEvent *event)
{
	setText(event->text());
	int key = event->key();
	this->getParent_size();
	switch (key) {
		case Qt::Key_Up:
			this->setText("Up");
			this->move(this->x(),this->y() - 5);
			if(this->y() <= 0){
				this->move(this->x(),0);
			}
			break;
		case Qt::Key_Down:
			this->setText("Down");
			this->move(this->x(),this->y() + 5);
			if(this->y() >= (this->parent_h - this->height())){
				this->move(this->x(), (this->parent_h - this->height()));
			}
			break;
		case Qt::Key_Left:
			this->setText("Left");
			this->move(this->x() - 5, this->y());
			if(this->x() <= 0){
				this->move(0 , this->y());
			}
			break;
		case Qt::Key_Right:
			this->setText("Right");
			this->move(this->x() + 5, this->y());
			if(this->x() >= (this->parent_w - this->width())){
				this->move((this->parent_w - this->width()) , this->y());
			}
			break;
		default:
			break;
	}
}

void KeyEvent::keyReleaseEvent(QKeyEvent *event)
{

}
